package edu.pitt.dbmi.odie.gapp.gwt.server.user;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.allen_sauer.gwt.log.client.Log;
import com.google.appengine.api.users.User;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.util.AuthenticationException;

import edu.pitt.dbmi.odie.gapp.gwt.server.navigator.ODIE_SelectionCacher;
import edu.pitt.dbmi.odie.gapp.gwt.server.util.gdata.ODIE_DocsServiceFetcher;

public class ODIE_UserUtils {
	
	private static final Logger log = Logger
	.getLogger(ODIE_UserUtils.class.getName());
	
	public static void main(String[] args) {
		try {
//			AuthSubUtil.revokeToken("CLzHvKUnEPm79_z4_____wE", null) ;
//			AuthSubUtil.revokeToken("CNbXzvG4EhCC95zjAQ", null) ;
			AuthSubUtil.revokeToken("CLzHvKUnEN7w6_AG", null) ;
			
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (GeneralSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String exchangeForAuthSubSessionToken(String authSubToken) {
		String authSubSessionToken = null ;
		try {
//			It appears that the protocol must be "http".  When set to https we get
//			Could not fetch URL: https://webodie.net/accounts/AuthSubSessionToken

			authSubSessionToken = AuthSubUtil.exchangeForSessionToken(
					"http", "webodie.net", authSubToken, null);
			log.info("exchangeForAuthSubSessionToken returns with " + authSubSessionToken) ;
//			if (authSubSessionToken == null) {
//				authSubSessionToken = AuthSubUtil.exchangeForSessionToken(authSubToken, null);
//				log.info("exchangeForAuthSubSessionToken returns with " + authSubSessionToken) ;
//			}
			if (authSubSessionToken == null) {
				authSubSessionToken = authSubToken ; // give up and try using the authSubToken
			}
			
		} catch (AuthenticationException e) {
			log.info("exchangeForAuthSubSessionToken: fails with " + e.getMessage()) ;
			authSubSessionToken = authSubToken ;
		} catch (IOException e) {
			log.info("exchangeForAuthSubSessionToken: fails with " + e.getMessage()) ;
			authSubSessionToken = authSubToken ;
		} catch (GeneralSecurityException e) {
			log.info("exchangeForAuthSubSessionToken: fails with " + e.getMessage()) ;
			authSubSessionToken = authSubToken ;
		}
		return authSubSessionToken ;
	}

	public static String assembleRequestUri(HttpServletRequest req) {
		String servletPath = req.getServletPath();
		StringBuffer requestURLBuffer = req.getRequestURL();
		String requestURL = (requestURLBuffer.length() > 0) ? requestURLBuffer
				.toString() : null;
		requestURL = requestURL.substring(0, requestURL
				.lastIndexOf(servletPath));
		return requestURL;
	}

	public static String reDirectToOdieClient(HttpServletRequest req,
			HttpServletResponse resp) {
		String servletPath = req.getServletPath();
		StringBuffer requestURLBuffer = req.getRequestURL();
		String requestURL = (requestURLBuffer.length() > 0) ? requestURLBuffer
				.toString() : null;
		requestURL = requestURL.substring(0, requestURL
				.lastIndexOf(servletPath));
		String reDirectUriName = requestURL + "/" + "ODIE_Client.html";
		return reDirectUriName;
	}

	public static void establishSessionCache(HttpServlet httpServlet,
			User user, String authSubToken, String authSubSessionToken) {
		ODIE_ServerSideLoginInfo serverSideLoginInfo = new ODIE_ServerSideLoginInfo();
		serverSideLoginInfo.setEmailAddress(user.getEmail());
		serverSideLoginInfo.setAuthSubToken(authSubToken) ;
		serverSideLoginInfo.setAuthSubSessionToken(authSubSessionToken);
		ODIE_DocsServiceFetcher.fetchOrCreateDocsService(httpServlet,
				serverSideLoginInfo);
		// establishUmlsConnectivity(docsService,
		// serverSideLoginInfo) ;
		ODIE_SelectionCacher selectionCacher = ODIE_SelectionCacher
				.fetchOrCreateOdieSelectionCacher(httpServlet);
		selectionCacher.fetchOrCreateUser(user.getEmail(), user.getNickname());
		selectionCacher.setLoginInfo(serverSideLoginInfo);
	}
	
	public static void establishSessionCache(HttpServlet httpServlet, ODIE_ServerSideLoginInfo serverSideLoginInfo) {
		ODIE_DocsServiceFetcher.fetchOrCreateDocsService(httpServlet,
				serverSideLoginInfo);
		ODIE_SelectionCacher selectionCacher = ODIE_SelectionCacher
				.fetchOrCreateOdieSelectionCacher(httpServlet);
		selectionCacher.fetchOrCreateUser(serverSideLoginInfo.getEmailAddress(), serverSideLoginInfo.getNickName());
		selectionCacher.setLoginInfo(serverSideLoginInfo);
	}

	@SuppressWarnings("unused")
	private String exchangeForSessionToken(String authSubToken) {
		String authSubSessionToken = null;
		if (authSubToken != null) {
			try {
				authSubSessionToken = AuthSubUtil.exchangeForSessionToken(
						"http", "webodie.net", authSubToken, null);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (GeneralSecurityException e) {
				e.printStackTrace();
			} catch (AuthenticationException e) {
				e.printStackTrace();
			}
		}
		return authSubSessionToken;
	}

	@SuppressWarnings("unchecked")
	private void displayRequestParameters(HttpServletRequest req, Logger log) {
		Map<String, Object> parameters = req.getParameterMap();
		for (String key : parameters.keySet()) {
			String diagnostic = key + " ==> " + req.getParameterMap().get(key);
			Log.debug(diagnostic);
			log.info(diagnostic);
		}
	}
}
